package com.kaibes.imserver.model;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.kaibes.imserver.KaibesIMServer;
import com.kaibes.imserver.control.UserSocketControl;
import com.kaibes.imserver.model.database.KaibesimcenterHelper;
import com.kaibes.imserver.model.utils.JsonParserUtil;

public class NotificationInterpreter {

	public final static int ACTION = 16;

	public static void explainServer(JsonParserUtil jsonParserUtil,
			UserSocketControl userSocketControl) {

		// 从json里获取ID
		int id = (int) jsonParserUtil.getJsonObjectSonValue("id");

		// 取得ID相关的数据
		ResultSet resultSet = KaibesimcenterHelper.getInstance()
				.getNotificationById(id);
		String contactname = null;
		int action = 0;
		try {
			if (resultSet != null && resultSet.next()) {
				contactname = resultSet.getString("contactname");
				action = Integer.parseInt(resultSet.getString("action"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String username = userSocketControl.getUserCenterData().getUsername();

		// 得到联系人soceket控制器
		UserSocketControl toClient = null;
		boolean ifFriendOnline = false;

		if ((toClient = KaibesIMServer.mainClientControl
				.getMainSocketControl(contactname)) != null) {
			ifFriendOnline = true;
		}

		switch (action) {
		// 纯消息
			case 1: {
			}
			break;

			// 用户返回了好友验证结果
			case 2: {
				boolean choice = (boolean) jsonParserUtil
						.getJsonObjectSonValue("choice");
				String message = null;
				int id_S = -1;

				if (choice) {
					KaibesimcenterHelper.getInstance().addContactEach(username,
							contactname);
					message = "用户" + username + "通过了你的好友请求！";
					id_S = 0;
				} else {
					message = "用户" + username + "拒绝了你的好友请求！";
					id_S = -1;
				}

				if (ifFriendOnline) {
					jsonParserUtil.newSelf(1, ACTION)
							.putJsonObjectSonValue("id", id_S)
							.putJsonObjectSonValue("action", 1)
							.putJsonObjectSonValue("contactname", username)
							.putJsonObjectSonValue("message", message)
							.commit(toClient.getClientStringWriter());
				} else {
					KaibesimcenterHelper.getInstance().addNotification(
							contactname, username, 1, message);
				}
			}

			break;

			default:
			break;
		}

		KaibesimcenterHelper.getInstance().removeNotification(id);

	}

}
